package com.yao.common.util;

import org.apache.ibatis.session.RowBounds;

import java.util.List;

/**
 * Created by haven on 2016/7/29.
 */
public final class PageUtils {
    private PageUtils() {

    }

    public static <T> PageResultDTO<T> genPageResult(List<T> list) {
        PageResultDTO<T> pageResultDTO = new PageResultDTO<>();
        if (list != null && list.size() > 0) {
            pageResultDTO.setData(list);
            pageResultDTO.setTotalRow(list.size());
        }
        return pageResultDTO;
    }

    public static RowBounds genRowBounds(BasePageQuery pageQuery) {
        int pageNum = pageQuery.getPageNum();
        int pageSize = pageQuery.getPageSize();
        return new RowBounds(pageNum * pageSize, pageSize);
    }

    /*public static CountBounds genCountBounds(BasePageQuery pageQuery, String countSQL) {
        int pageNum = pageQuery.getPageNum();
        int pageSize = pageQuery.getPageSize();
        return new CountBounds(pageNum * pageSize, pageSize, countSQL);
    }*/

    public static void fillPageResponse(PageResponseDTO pageResponseDTO, BasePageQuery query, int totalCount) {
        if (query.getPageSize() == 0) {
            pageResponseDTO.setTotal(10);
        } else {
            int remainder = totalCount % query.getPageSize() == 0 ? 0 : 1;
            pageResponseDTO.setTotal(totalCount / query.getPageSize() + remainder);
        }
        pageResponseDTO.setRecords(totalCount);
    }

    public static <M> PageResponseDTO<M> getPageResponseDTO(PageResultDTO<M> pageResultDTO, int pageSize) {
        PageResponseDTO<M> pageResponseDTO = new PageResponseDTO<>();
        int totalCount = 0;
        if (pageResultDTO != null) {
            pageResponseDTO.setRows(pageResultDTO.getData());
            pageResponseDTO.setTotal(pageResultDTO.getTotalRow());
            totalCount = pageResultDTO.getTotalRow();
        }
        fillPageResponse(pageResponseDTO, new BasePageQuery().setPageSize(pageSize), totalCount);
        return pageResponseDTO;
    }

    public static <P, M> PageResponseDTO<M> getPageResponseDTO(PageQueryOp<P, M> op, P p, int pageSize) {
        PageResultDTO<M> pageResultDTO = op.getPage(p);
        return getPageResponseDTO(pageResultDTO, pageSize);
    }

    @FunctionalInterface
    public interface PageQueryOp<P, M> {
        PageResultDTO<M> getPage(P p);
    }
}
